package com.imchen.cms.cmscommon.utils;

import com.imchen.cms.exception.CmsException;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;

/**
 * @author imchen
 * @create: 2019-01-18 06:25
 **/
public class ServiceUtil {

    public static HashMap<String,Object> toObjectMap(Object object, String key){
        HashMap<String,Object> userMap=null;
        if (object==null){
            return null;
        }
        userMap=new HashMap<>();
        userMap.put(key,object);
        return userMap;
    }

    public static HashMap<String,Integer> toAddMap(int count,int id){
        HashMap<String,Integer> map =new HashMap<>();
        map.put("count",count);
        map.put("id",id);
        return map;
    }

    public static ResponseEntity<Resource> view(String filePath) throws CmsException, FileNotFoundException {
        File file =new File(filePath);
        if (!file.exists()||file.isDirectory()){
            throw new CmsException("File not found or is directory",404);
        }
        FileInputStream inputStream = new FileInputStream(file);
        InputStreamResource resource=new InputStreamResource(inputStream);
        HttpHeaders headers=new HttpHeaders();
        return new ResponseEntity<>(resource,headers, HttpStatus.OK);
    }
}
